<?php
namespace App\Http\Controllers;

use Illuminate\Support\Facades\DB;
use App\Models\Love;
use Illuminate\Support\Facades\Schema;

class LoveController extends WxBaseController{
    //是否收藏
    public function index($model,$id){
        $love = Love::where(['target_id'=>$id,'model'=>$model,'wxuser_id'=>$this->auth()->id])->get();
        if(!$love->isEmpty()){
            return $this->apiReturn(true,'已收藏');
        }else{
            return $this->apiReturn(false,'未收藏');
        }
    }
    public function love(){
        $input = request();
        $params =[
            'model'=>$input->model,
            'target_id'=>$input->target_id,
            'wxuser_id'=>$this->auth()->id,
        ];
        //更新收藏量
        if(Love::where(['model'=>$input->model,'target_id'=>$input->target_id,'wxuser_id'=>$this->auth()->id])->count()){
            return $this->apiReturn(true,'已收藏');
        }else{
            if(Schema::hasColumn($input->model, 'star')){
                $love = Love::updateOrCreate($params);
                DB::table($input->model)->where('id',$input->target_id)->increment('star');
                return $this->apiReturn(true,'success',$love);
            }
            else{
                return $this->apiReturn(false,'不存在star字段');
            }
        }
    }
    public function unlove(){
        $input = request();
        //更新收藏量
        if(Schema::hasColumn($input->model, 'star')){
            $model = DB::table($input->model);
            if($model) {
                $model->where('id',$input->target_Id)->decrement('star');
                //删除收藏信息
                $num = Love::destroy($input->id);
                if($num>0){
                    return $this->apiReturn(true,'取消成功');
                }else{
                    return $this->apiReturn(false,'取消失败');
                }

            }
        }else{
            return $this->apiReturn(false,'找不到start字段');
        };
    }
}